package com.markerhub.controller;


import com.markerhub.common.lang.Result;
import com.markerhub.entity.User;
import com.markerhub.entity.LoginUser;
import com.markerhub.handler.Wx_Token_Auth;
import com.markerhub.repository.LoginUserRepository;
import com.markerhub.repository.UserRepository;
import com.markerhub.service.UserService;
import com.markerhub.vo.WXAuth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Optional;

/**
 * 前端控制器
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Resource
    private LoginUserRepository loginUserRepository;

    @Resource
    private UserRepository userRepository;

    /**
     * 获取sessionId
     *
     * @param code
     * @return
     */
    @PostMapping("code")
    public Result getSessionId(@RequestBody String code) {
        return userService.getSessionId(code);
    }

    /**
     * 调用 auth.code2Session 接口，换取 用户唯一标识 OpenID
     * 用户在微信开放平台帐号下的唯一标识UnionID（若当前小程序已绑定到微信开放平台帐号） 和 会话密钥 session_key
     *
     * @param wxAuth
     * @return
     */
    @PostMapping("/authLogin")
    public Result authLogin(@RequestBody WXAuth wxAuth) {
        Result result = userService.authLogin(wxAuth);
        //绑定日志
        log.info("{}", result);
        return result;
    }

    /**
     * url ://user/1
     * 根据id查询user信息
     *
     * @param id
     * @return null或者user
     */
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Integer id) {
        Optional<User> user = userRepository.findById(id);
        /**
         * 如果user是null则返回null，否则返回user
         */
        return user.orElseGet(null);
    }

    /**
     * @param loginUser
     * @return
     */
    @PostMapping("/login")
    public LoginUser login(@RequestBody LoginUser loginUser) {
        return loginUserRepository.findByUsernameAndPassword(loginUser.getUsername(), loginUser.getPassword());
    }

    /**
     * 根据token来验证此token是否有效
     *
     * @param refresh
     * @return
     */
    @GetMapping("userinfo")
    public Result userinfo(@RequestHeader("Authorization") String token, Boolean refresh) {
        return userService.userInfo(refresh);
    }

    /**
     * 绑定用户手机号
     *
     * @param jsonBody
     * @return
     */
    @Wx_Token_Auth
    @PostMapping("bindUserPhone")
    public Result bindUserPhone(@RequestBody Map<String, String> jsonBody) {
        String phone = jsonBody.get("phone");
        int userId = Integer.parseInt(jsonBody.get("userId"));
        Result result = userService.bindUserPhone(userId, phone);
        log.info("{}", result);
        return result;
    }


}
